ARTICLEViews: 6Share  Posted by - Anonymous

interview question - function to convert given string to object a.b.c = "test"

function to convert given string to object

input: 

a.b.c = "test"


output: 

{ a : { b : { c : "test" } } }


Solution:



function getObj(key, value){

 const rtnObj = {};

  

 const subKeys = key.split(".");


 const getNestedKey = (obj, nextKey, value) => {

  obj[nextKey] = value;

 }


 if(subKeys.length){

  let currObj = rtnObj;

  for(let i =0; i < subKeys.length; i++){ // 0 , 1 , 2

    

   if(i + 1 === subKeys.length){  

    console.log("last key", subKeys[i]);

    currObj[subKeys[i]] = value;

   }

   else {

    currObj[subKeys[i]] = {};

   }

   currObj = currObj[subKeys[i]];

  }


 }


 return rtnObj;

}


console.log(getObj("a.b.c", "test"));


In this video, I have explained one famous Java Interview Question: How To Count Occurrences Of Each Character In String In ...

HOW CHINESE STUDENTS SO FAST IN SOLVING MATH OVER AMERICAN STUDENTS

Important Interview Question: How to Print count of duplicate characters from String? || #Hackerrank

IQ TEST

String Array To String || Integer Array To Integer || Mini Java Interview Questions Series



Views -